package networks.protocol;

public class PackageProtocol {

    private static final int HEADER_LENGTH = 5;

    /**
     * 系统消息，握手/心跳
     * 
     * @param type
     * @return
     */
    public static byte[] Encode(PackageType type) {
        byte[] bytes = new byte[5];
        bytes[0] = 1 >> 24 & 0xFF;
        bytes[1] = 1 >> 16 & 0xFF;
        bytes[2] = 1 >> 8 & 0xFF;
        bytes[3] = 1 & 0xFF;
        bytes[4] = type.ToByte();

        return bytes;
    }

    public static byte[] Encode(PackageType type, byte[] message) {
        int msgLength = message == null ? 0 : message.length;
        byte[] bytes = new byte[msgLength + HEADER_LENGTH];
        int length = msgLength + 1;

        int index = 0;
        bytes[index++] = (byte) (length >> 24 & 0xFF);
        bytes[index++] = (byte) (length >> 16 & 0xFF);
        bytes[index++] = (byte) (length >> 8 & 0xFF);
        bytes[index++] = (byte) (length & 0xFF);
        bytes[index++] = type.ToByte();

        while (index < msgLength + HEADER_LENGTH) {
            bytes[index] = message[index - HEADER_LENGTH];
            index++;
        }

        return bytes;
    }

    public static Package Decode(byte[] bytes) {
        PackageType type = PackageType.ToEnum(bytes[4]);
        byte[] body = new byte[bytes.length - HEADER_LENGTH];

        for (int i = 0; i < body.length; i++) {
            body[i] = bytes[i + HEADER_LENGTH];
        }

        return new Package(type, body);
    }
}
